package com.atguigu.spzx.manager.service.impl;

import com.atguigu.spzx.common.constant.SysUserStatusEnum;
import com.atguigu.spzx.common.entity.SysUser;
import com.atguigu.spzx.manager.custom.CustomUser;
import com.atguigu.spzx.manager.manager.PermissionManager;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 自定义userDetailService
 * </p>
 *
 * @author flyduck
 * @since 2023/10/26
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PermissionManager permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserMapper.getUserByUsername(username);

        if (sysUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        if (SysUserStatusEnum.STOP.getCode().equals(sysUser.getStatus())) {
            throw new RuntimeException("用户已经被禁用");
        }
        //查询权限数据
        List<String> permissionList = permissionService.getUserPermsListByUserId(sysUser.getId());
        //转换为security要求的对象
        List<SimpleGrantedAuthority> authorities = permissionList.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());

        return new CustomUser(sysUser, authorities);
    }
}
